package com.boot.web.config;

import cn.hutool.core.io.FileUtil;
import com.boot.web.controller.ApplicationController;
import com.boot.web.exception.BootHandlerExceptionResolver;
import com.boot.web.exception.ExceptionHandlerManager;
import com.boot.web.exception.ModuleExceptionHandler;
import com.boot.web.exception.handler.GlobalExceptionHandler;
import com.boot.web.log.LogAspect;
import com.boot.web.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.net.InetAddress;
import java.util.List;

/**
 * @author 霜寒 <1621856595@qq.com>
 * @description 配置拦截器和资源地址
 * @date 2019/5/20 15:37
 **/
@Slf4j
@EnableConfigurationProperties(ResourceProperties.class)
@Import({ApplicationController.class,
        BootHandlerExceptionResolver.class, GlobalExceptionHandler.class,
        LogAspect.class})
@EnableRetry
@Configuration
public class WebAutoConfiguration implements WebMvcConfigurer {

    /**
     * @author 霜寒 <1621856595@qq.com>
     * @description 配置跨域
     * @date 2020/3/10 20:10
     **/
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowCredentials(false)
                .allowedHeaders("*")
                .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTION", "HEAD", "TRACE")
                .allowedOrigins("*")
                .exposedHeaders("Authorization", "Upgrade", "Token");
    }

    @Autowired
    private ResourceProperties resourceProperties;

    public void check(ResourceProperties properties) {
        if (!FileUtil.exist(properties.getSafeOpenRoute())) {
            FileUtil.mkdir(properties.getSafeOpenRoute());
        }
        if (!FileUtil.isDirectory(properties.getSafeOpenRoute())) {
            throw new RuntimeException("openRoute不是文件夹");
        }
        if (!FileUtil.exist(properties.getSafeClosedRoute())) {
            FileUtil.mkdir(properties.getSafeClosedRoute());
        }
        if (!FileUtil.isDirectory(properties.getSafeClosedRoute())) {
            throw new RuntimeException("closedRoute不是文件夹");
        }
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        check(resourceProperties);
        registry.addResourceHandler("/openRoute/**")
                .addResourceLocations("file:" + resourceProperties.getSafeOpenRoute());
        InetAddress address = IpUtil.getFirstNonLoopBackAddress();
        if (address == null) {
            log.info("开放文件路由：{}", resourceProperties.getSafeOpenRoute());
        } else {
            log.info("{} 开放文件路由：{}", address.getHostAddress(), resourceProperties.getSafeOpenRoute());
        }
    }

    @Autowired
    private ModuleExceptionHandler[] handlers;

    @Bean
    ExceptionHandlerManager exceptionHandlerManager() {
        ExceptionHandlerManager manager = new ExceptionHandlerManager();
        for (ModuleExceptionHandler handler : handlers) {
            manager.addHandler(handler);
        }
        List<ModuleExceptionHandler> modules = manager.apply().getHandlers();
        StringBuilder builder = new StringBuilder();
        for (ModuleExceptionHandler module : modules) {
            builder.append(',').append(module.getClass().getSimpleName());
        }
        builder.append("已加入业务错误处理机制");
        log.info(builder.substring(1));
        return manager;
    }

}
